package com.moyu.crowdsource.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moyu.crowdsource.entity.AccountUser;
import com.moyu.crowdsource.entity.Address;
import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.entity.CommodityOrder;
import com.moyu.crowdsource.service.AccountUserService;
import com.moyu.crowdsource.service.AddressService;
import com.moyu.crowdsource.service.CommodityImageService;
import com.moyu.crowdsource.service.CommodityOrderService;
import com.moyu.crowdsource.util.CommonErrorHandle;
import com.moyu.crowdsource.util.Msg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;

@Api(
  value = "二手商品controller",
  tags = {"商品订单接口"}
)
@RestController
@RequestMapping("${api.base}/commodityorder")
public class CommodityOrderController {

  @Autowired CommodityOrderService commodityOrderService;

  @Autowired CommodityImageService commodityImageService;

  @Autowired AccountUserService accountUserService;

  @Autowired AddressService addressService;

  @ApiOperation("发布订单")
  @PostMapping("/submitorder")
  public Msg submitOrder(@Valid CommodityOrder commodityOrder, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
      return Msg.fail().add("errorFields", CommonErrorHandle.getErrorInfo(bindingResult));
    }

    commodityOrder.setProfit(BigDecimal.ONE);
    commodityOrder.setPayStatus("未支付");
    commodityOrderService.submitOrder(commodityOrder);
    return Msg.success().add("info", "订单发布成功");
  }

  @ApiOperation("发布订单附加图片")
  @PostMapping("/submitorderandimg")
  public Msg submitOrderAndImage(
      @Valid CommodityOrder commodityOrder,
      BindingResult bindingResult,
      MultipartFile multfile1,
      MultipartFile multfile2,
      MultipartFile multfile3,
      CommodityImage commodityImage) {

    if (bindingResult.hasErrors()) {
      return Msg.fail().add("errorFields", CommonErrorHandle.getErrorInfo(bindingResult));
    }
    if(null==multfile1){
        return Msg.fail().add("errorFields","至少上传一个图片");
    }
    commodityOrder.setProfit(BigDecimal.ONE);
    return commodityOrderService.submitOrderAndImg(commodityOrder, multfile1,multfile2,multfile3, commodityImage).add("info", "订单发布成功");
  }

  @ApiOperation("订单支付成功调用")
  @PostMapping("/paysuccess/{commodityOrderId}")
  public Msg updateCommodityOrder(
      String clientUserId,
      String addressId,
      @PathVariable("commodityOrderId") String commodityOrderId) {
    CommodityOrder commodityOrderdab =
        commodityOrderService.getCommodityOrderByOrderId(commodityOrderId);
    if (commodityOrderdab.getIssueUserId() == Integer.valueOf(clientUserId)) {
      return Msg.fail().addInfo("无法购买自己发布的物品");
    }

    calculationMoneyAndUpdate(commodityOrderdab);
    /*    Double money= Double.valueOf(accountUser.getPaymoney());
    BigDecimal offerPrice=commodityOrderdab.getOfferPrice();
    BigDecimal profit=commodityOrderdab.getProfit();
    BigDecimal finalMoney=BigDecimal.valueOf(money).add(offerPrice).subtract(profit);
    String userId = accountUser.getUserId();
    AccountUser newAccout=new AccountUser();
    newAccout.setUserId(userId);
    newAccout.setPaymoney(finalMoney.toString());
    accountUserService.updateAccount(newAccout);*/

    CommodityOrder commodityOrder = new CommodityOrder();
    Address address = addressService.getUserAddressByAddressId(addressId);
    commodityOrder.setCommodityOrderId(commodityOrderId);
    commodityOrder.setAddress(address.getAddress());
    commodityOrder.setMobile(address.getMobile());
    commodityOrder.setStatus("配送中");
    commodityOrder.setPayStatus("已支付");
    commodityOrder.setClientUserId(Integer.valueOf(clientUserId));
    commodityOrderService.updateCommodityOrder(commodityOrder);
    return Msg.success().addInfo("订单交易成功");
  }

  public void calculationMoneyAndUpdate(CommodityOrder commodityOrderdab) {
    Integer userId = commodityOrderdab.getIssueUserId();
    AccountUser accountUser = accountUserService.getAccountInfo(userId);

    Double money = Double.valueOf(accountUser.getPaymoney());
    BigDecimal offerPrice = commodityOrderdab.getOfferPrice();
    BigDecimal profit = commodityOrderdab.getProfit();
    BigDecimal finalMoney = BigDecimal.valueOf(money).add(offerPrice).subtract(profit);

    AccountUser newAccout = new AccountUser();
    newAccout.setUserId(String.valueOf(userId));
    newAccout.setPaymoney(finalMoney.toString());
    accountUserService.updateAccount(newAccout);
  }

  @ApiOperation("获取所有订单(所有)")
  @GetMapping("/query/getallorder")
  public Msg getAllOrder(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
    PageHelper.startPage(pn, 10);
    List<CommodityOrder> commodityOrders = commodityOrderService.getAllOrder();
    PageInfo pageInfo = new PageInfo(commodityOrders);
    return Msg.success().add("allCommodityOrder", pageInfo);
  }

  @ApiOperation("获取所有有效订单")
  @GetMapping("/query/getvaildorder")
  public Msg getVaildOrder(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
    PageHelper.startPage(pn, 10);
    List<CommodityOrder> commodityOrders = commodityOrderService.getValidOrder();
    PageInfo pageInfo = new PageInfo(commodityOrders);
    if (pageInfo.getPageNum() == pn) return Msg.success().add("vaildCommodityOrder", pageInfo);
    else return Msg.fail().add("info", "在看也没有了");
  }

  @ApiOperation("获取所有有效订单附加图片")
  @GetMapping("/query/getvaildorderandimg")
  public Msg getVaildOrderAndImage(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
    PageHelper.startPage(pn, 10);
    List<CommodityOrder> commodityOrders = commodityOrderService.getValidOrderAndImage();
    PageInfo pageInfo = new PageInfo(commodityOrders);
    return Msg.success().add("vaildCommodityOrder", pageInfo);
  }

  @ApiOperation("搜索订单")
  @GetMapping("/query/conditional")
  public Msg getOrderConditionalQuery(
      @RequestParam(value = "pn", defaultValue = "1") Integer pn,
      String goodName,
      String variety,
      @RequestParam(defaultValue = "已发布") String status) {
    PageHelper.startPage(pn, 10);
    List<CommodityOrder> commodityOrders =
        commodityOrderService.getOrderConditionalQuery(goodName, variety, status);
    PageInfo pageInfo = new PageInfo(commodityOrders);
    return Msg.success().add("vaildCommodityOrder", pageInfo);
  }

  @ApiOperation("获取单个订单详情")
  @GetMapping("/query/getvaildorderandimg/{commodityOrderId}")
  public Msg getVaildOrderAndImage(@PathVariable("commodityOrderId") String commodityOrderId) {

    CommodityOrder commodityOrder =
        commodityOrderService.getValidOrderAndImageById(commodityOrderId).get(0);
    if (null != commodityOrder.getClientUserId()) {
      return Msg.success()
          .add("vaildCommodityOrder", commodityOrder)
          .add("issue", accountUserService.getAccountInfo(commodityOrder.getIssueUserId()))
          .add("client", accountUserService.getAccountInfo(commodityOrder.getClientUserId()));
    }
    return Msg.success()
        .add("vaildCommodityOrder", commodityOrder)
        .add("issue", accountUserService.getAccountInfo(commodityOrder.getIssueUserId()));
  }

  @ApiOperation("通过ID查询发布者发布的订单")
  @GetMapping("/query/{issueUserId}")
  public Msg getOrderByissueUserId(@PathVariable("issueUserId") Integer issueUserId, String... args) {
    return Msg.success().add("yourOrders", commodityOrderService.getOrderByIssueId(issueUserId,args));
  }

  @ApiOperation("通过发布者ID查询订单,状态暂时分为:已发布，配送中，已删除")
  @GetMapping("/query/status/{issueUserId}")
  public Msg getOrderByissueUserIdAndStatus(
      @PathVariable("issueUserId") Integer issueUserId,
      @RequestParam(defaultValue = "已发布") String status) {
    return Msg.success()
        .add("yourOrders", commodityOrderService.getOrderByIssueIdAndStatus(issueUserId, status));
  }

  @ApiOperation("通过购买者ID查询订单")
  @GetMapping("/query/client/{clientUserId}")
  public Msg getOrderByclientUserId(@PathVariable("clientUserId") Integer clientUserId) {
    return Msg.success()
        .add("yourOrders", commodityOrderService.getOrderByClientIdAndStatus(clientUserId, "配送中"));
  }

  @ApiOperation("更新发布的订单")
    @PutMapping("/update/{commodityOrderId}")
    public Msg updateCommodityOrder(CommodityOrder commodityOrder) {
        commodityOrderService.updateCommodityOrder(commodityOrder);
        return Msg.success().add("info", "订单信息更新成功");
    }

    @ApiOperation("确认收货调用接口")
    @PutMapping("/update/received/{commodityOrderId}")
    public Msg updateCommodityOrder(@PathVariable("commodityOrderId") String commodityOrderId) {
        CommodityOrder commodityOrder=new CommodityOrder();
        commodityOrder.setCommodityOrderId(commodityOrderId);
        commodityOrder.setStatus("已收货");
        commodityOrderService.updateCommodityOrder(commodityOrder);
        return Msg.success().add("info", "订单信息确认收货成功");
    }

  @ApiOperation("彻底删除发布的订单")
  @DeleteMapping("/del/{commodityOrderId}")
  public Msg delCommodityOrder(@PathVariable("commodityOrderId") String commodityOrderId) {
    commodityOrderService.delCommodityOrder(commodityOrderId);
    return Msg.success().add("info", "订单删除成功");
  }

  @ApiOperation("非彻底删除订单")
  @DeleteMapping("/notrealdel/{commodityOrderId}")
  public Msg notRealDelCommodityOrder(@PathVariable("commodityOrderId") String commodityOrderId) {
    CommodityOrder commodityOrder = new CommodityOrder();
    commodityOrder.setCommodityOrderId(commodityOrderId);
    commodityOrder.setStatus("DELETE");
    commodityOrderService.updateCommodityOrder(commodityOrder);
    return Msg.success().add("info", "删除成功");
  }
}
